package com.wk.springboot.httpUtils;

import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class DrspHttpPost extends DrspHttpMethod {

    private HttpPost httpPost = new HttpPost();

    public DrspHttpPost(CloseableHttpClient httpClient) {
        super(httpClient);
    }

    public DrspHttpResponse execute() throws ClientProtocolException, IOException {
        return new DrspHttpResponse(this.httpClient.execute(httpPost));
    }

    /**
     * 释放连接
     * @param requestBase
     */
    @Override
    public void releaseConnection() {
        this.httpPost.releaseConnection();
    }

    public DrspHttpPost setFormParams(Map<String, String> formParams) throws UnsupportedEncodingException {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(formParams.size());
        for (Map.Entry<String, String> entry : formParams.entrySet()) {
            pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET_UTF8_STR));
        return this;
    }

    public DrspHttpPost setBody(String body) {
        ContentType contentType = ContentType.create(this.contentType, CHARSET_UTF8);
        StringEntity entity = new StringEntity(body, contentType);
        entity.setContentEncoding(CHARSET_UTF8_STR);
        this.httpPost.setEntity(entity);
        return this;
    }

    public DrspHttpPost setBody(InputStream stream) {
        this.httpPost.setEntity(new InputStreamEntity(stream));
        return this;
    }

    public DrspHttpPost setMultiPartBuilder(MultipartEntityBuilderWraper entityBuilder) {
        this.httpPost.setEntity(entityBuilder.build());
        return this;
    }

    public DrspHttpMethod setContentType(String contentType) {
        this.contentType = contentType;
        return this;
    }

    public DrspHttpPost setUrl(String url) {
        Preconditions.checkArgument(StringUtils.isNotBlank(url), "http调用时url为空");
        this.url = url;
        this.httpPost.setURI(URI.create(url));
        return this;
    }

}
